package com.star.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.star.constant.MessageConstant;
import com.star.constant.StatusConstant;
import com.star.context.BaseContext;
import com.star.dto.AdminDTO;
import com.star.dto.AdminLoginDTO;
import com.star.dto.BusinessPageQueryDTO;
import com.star.dto.PasswordEditDTO;
import com.star.entity.Admin;
import com.star.exception.AccountLockedException;
import com.star.exception.AccountNotFoundException;
import com.star.exception.PasswordErrorException;
import com.star.mapper.AdminMapper;
import com.star.result.PageResult;
import com.star.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录
     * @param adminLoginDTO
     * @return
     */
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传来的密码进行加密与数据库密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (admin.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return admin;
    }

    /**
     * 管理员分页查询
     * @param businessPageQueryDTO
     * @return
     */
    public PageResult pageQuery(BusinessPageQueryDTO businessPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(businessPageQueryDTO.getPage(), businessPageQueryDTO.getPageSize());
        Page<Admin> page = adminMapper.pageQuery(businessPageQueryDTO);
        long total = page.getTotal();
        List<Admin> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 管理员状态
     * @param status
     * @param id
     */
    public void updateStatus(Integer status, Long id) {
        Admin admin = adminMapper.getById(id);
        admin.setStatus(status);
        adminMapper.update(admin);
    }

    /**
     * 添加管理员
     * @param adminDTO
     */
    public void add(AdminDTO adminDTO) {
        Admin admin = new Admin();
        // 对象属性拷贝
        BeanUtils.copyProperties(adminDTO, admin);
        // 设置账户状态, 默认状态 1:正常 0:禁用
        admin.setStatus(StatusConstant.ENABLE);
        // 设置默认密码: 身份证后六位
        String pwd = "123456";
        admin.setPassword(DigestUtils.md5DigestAsHex(pwd.getBytes()));
        adminMapper.insert(admin);
    }

    /**
     * 根据id查询管理员信息
     * @param id
     */
    public Admin getById(Long id) {
        Admin adminDB = adminMapper.getById(id);
        return adminDB;
    }

    /**
     * 更新
     * @param adminDTO
     */
    @Transactional
    public void update(AdminDTO adminDTO) {
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDTO, admin);

        adminMapper.update(admin);
    }

    /**
     * 修改头像
     * @param id
     * @param avatar
     */
    public void updateAvatar(Long id, String avatar) {
        Admin admin = adminMapper.getById(id);
        admin.setAvatar(avatar);
        adminMapper.update(admin);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    public void updatePwd(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setId(BaseContext.getCurrentId());
        Admin admin = adminMapper.getById(passwordEditDTO.getId());
        // 加密输入旧密码
        String oldPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        if(!oldPwd.equals(admin.getPassword())) {
            // 原密码错误
            throw new PasswordErrorException(MessageConstant.OLD_PASSWORD_ERROR);
        }
        // 更新密码
        admin.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));

        // 公共字段自动注入:update_time,update_user

        adminMapper.update(admin);
    }


}
